package cn.dianchiyun.protocol.netty.dtu.handler.impl;

import cn.dianchiyun.protocol.netty.utils.ByteUtil;
import cn.dianchiyun.protocol.netty.utils.HexUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class StringDecoderHandler extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        String HEXES = "0123456789ABCDEF";
        byte[] bytes = new byte[msg.readableBytes()];
        msg.readBytes(bytes);

        if(bytes[0] == 0x7E){
            System.out.println("~~~~~~~~~~~~~~~~~~~");
        }

        int indexNow = 7;
            /*byte[] code = Arrays.copyOfRange(bytes, indexNow, indexNow + 12);
            indexNow += 12;
            System.out.println(new String(code));*/

        byte address = bytes[indexNow];
        indexNow += 1;
        System.out.println("address char:" + address);
        if (address == 0x01) {
            System.out.println("address:" + HexUtil.bytes2Byte255(address));
        }

        byte funCode = bytes[indexNow];
        indexNow += 1;
        System.out.println("funCode char:" + (char) funCode);
        if (funCode == 0x04) {
            System.out.println("funCode:" + HexUtil.bytes2Byte255(funCode));
        }

        byte lengthByte = bytes[indexNow];
        indexNow += 1;
        int dataLength = HexUtil.bytes2Byte255(lengthByte) / 2;

        System.out.print("长度:"+dataLength);

        System.out.print("数据:");
        for (int i = 0; i < dataLength; i++) {
            System.out.print(ByteUtil.getInt(new byte[]{bytes[indexNow + 1], bytes[indexNow]}, true) + "\t");
            indexNow += 2;
        }
        System.out.println("\t");

        System.out.println(bytes.length);
        final StringBuilder hex = new StringBuilder(2 * bytes.length);

        for (int i = 0; i < bytes.length; i++) {
            byte b = bytes[i];
            hex.append(HEXES.charAt((b & 0xF0) >> 4))
                    .append(HEXES.charAt((b & 0x0F)));
        }
        out.add(hex.toString());
    }

}